const fs = require('fs');
const path = require('path');
const os = require('os');
const { app, protocol } = require('electron')
const uuid=require('uuid');

app.whenReady().then(() => {
    //注册FileProtocol
    protocol.interceptFileProtocol('file', (req, callback) => {
        //去除file:///
        const url = req.url.substr(8);
        callback(decodeURI(url));
    }, (error) => {
        if (error) {
            console.error('Failed to register protocol');
        }
    });
})
//关闭事件
app.on("before-quit",()=>{
    //删除文件夹
    console.log("出发关闭事件",global.filePath)
    global.filePath && FileDelPathAll(global.filePath)
})
//递归删除目录
function FileDelPathAll(path) {
    var files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
            var curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) { // recurse
                FileDelPathAll(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}
//递归创建多级目录
function mkdirsSync(dirname) {  
    //console.log(dirname);  
    if (fs.existsSync(dirname)) {  
        return true;  
    } else {  
        if (mkdirsSync(path.dirname(dirname))) {  
            fs.mkdirSync(dirname);  
            return true;  
        }  
    }  
} 

global.filePath = global.filePath||null;

function globalFile(id){
    //判断临时目录是否存在
    global.filePath = path.join(os.tmpdir(), 'autojs-au');
    let filePath=path.join(global.filePath,id)
    try{
        var stat = fs.statSync(filePath);
        if (stat.isDirectory()) {
            //删除目录
            FileDelPathAll(filePath);
        }
    }catch(e){}
    mkdirsSync(filePath);
    return filePath;
}

export default {
    /**
     * 根据图片流创建文件，成功：code=200，info=图片路径
     * @param {buffer} imageBuffer 图片流
     */
    createdFile(imageBuffer) {
        return new Promise((resolve, rej) => {
            let id = uuid.v4();
            let imgPath = path.join(globalFile(id), uuid.v4()+ '.png');
            fs.writeFile(imgPath, imageBuffer, function (err) {//用fs写入文件
                if (err) {
                    resolve({
                        code: 500,
                        id:id,
                        info: err.message
                    });
                } else {
                    resolve({
                        code: 200,
                        id:id,
                        info: imgPath
                    });
                }
            })
        })
    },
    globalFile,
    //生成临时文件路径
    createdFilePath(pid){
        let id = uuid.v4();
        return path.join(global.filePath,  pid+'/'+id + '.png');
    },
    getImageFilePath(pid){
        return path.join(global.filePath,  pid);
    },
    FileDelPathAll
}

